<?php
declare (strict_types = 1);
namespace app\admin\model\data;

use app\common\model\ProductType;

/**
 * 访问记录历史
 */
class Visit extends DataModel
{
    /**
     * 表名
     * @var string
     */
    protected $name = 'website_visit';

    /**
     * 获取资源的产品类型ID
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-17
     * @param    string                         $resource_type [description]
     * @return   [type]                                        [description]
     */
    public static function getProductType($resource_type = '')
    {
        $product = [
            'video'      => ProductType::getProductIdByKey('video'),
            'live'       => ProductType::getProductIdByKey('live'),
            'offline'    => ProductType::getProductIdByKey('offline'),
            'live_small' => ProductType::getProductIdByKey('live'),
            'classes'    => ProductType::getProductIdByKey('classes'),
        ];

        return $product[$resource_type] ?? 1;
    }

    /**
     * 访问量排行分页数据
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-23
     * @param    [type]                         $resource_type [description]
     * @param    [type]                         $timespan      [description]
     * @return   [type]                                        [description]
     */
    public static function getVisitRankPageList(array $resource_type = [], $timespan = [])
    {
        $builder  = (new Visit())->scope('mhm');
        $pagesize = Visit::getListRows();
        // 是否包含类型
        if ($resource_type) {
            $builder = $builder->whereIn('resource_type', $resource_type);
        }
        // 是否限定了时间段
        if ($timespan) {
            $builder = $builder->whereBetween('visit_time', $timespan);
        }

        return $builder->field(['SUM(pv)' => 'tp_pv', 'resource_type', 'resource_id', 'COUNT(DISTINCT ip)' => 'tp_uv'])->group('resource_type,resource_id')->order('tp_pv', 'desc')->paginate($pagesize);

    }

    /**
     * 获取资源的访问情况
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-26
     * @param    [type]                         $resource_type [description]
     * @param    [type]                         $resource_id   [description]
     * @return   [type]                                        [description]
     */
    public static function getResourceVisit($resource_type, $resource_id, $timespan = [])
    {
        $builder = (new Visit())->where('resource_type', $resource_type)->where('resource_id', $resource_id)->field(['SUM(pv)' => 'tp_pv', 'COUNT(DISTINCT ip)' => 'tp_uv']);
        if ($timespan) {
            $builder = $builder->whereBetween('visit_time', $timespan);
        }

        $visit = $builder->find();

        $visit['tp_pv'] = floatval($visit['tp_pv']);

        return $visit;
    }
}
